package protocol.telnet;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.ssl.SslContext;

import java.nio.charset.Charset;

public class TelnetClientInitializer extends ChannelInitializer<SocketChannel> {

    private static final StringDecoder DECODER = new StringDecoder(Charset.forName("GBK"));
    private static final StringEncoder ENCODER = new StringEncoder(Charset.forName("GBK"));

    private static final TelnetClientHandler CLIENT_HANDLER = new TelnetClientHandler();

    private final SslContext sslContext;

    public TelnetClientInitializer(SslContext sslCtx) {
        this.sslContext = sslCtx;
    }

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        if (sslContext != null) {
            // ssl
            pipeline.addLast(sslContext.newHandler(ch.alloc(), TelnetClient.HOST, TelnetClient.PORT));
        }



        pipeline.addLast(ENCODER);
        pipeline.addLast(DECODER);

        pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));

        pipeline.addLast(CLIENT_HANDLER);
    }
}
